<template>
  <view class="container">
    <view class="form-container">
      <!-- 宠物选择 -->
      <view class="form-item">
        <text class="form-label">宠物<text class="required">*</text></text>
        <picker 
          mode="selector" 
          :range="pets" 
          :range-key="getPetDisplayField()"
          @change="onPetChange"
          :value="petIndex"
          class="picker"
          disabled
        >
          <view class="picker-text" style="color: #999;">{{selectedPetName || '请选择宠物'}}</view>
        </picker>
      </view>

      <!-- 记录类型 -->
      <view class="form-item">
        <text class="form-label">记录类型<text class="required">*</text></text>
        <picker 
          mode="selector" 
          :range="typeOptions" 
          range-key="label"
          @change="onTypeChange"
          :value="typeIndex"
          class="picker"
        >
          <view class="picker-text">{{formData.type || '请选择记录类型'}}</view>
        </picker>
      </view>

      <!-- 记录内容 -->
      <view class="form-item">
        <text class="form-label">记录内容<text class="required">*</text></text>
        <textarea 
          v-model="formData.content" 
          placeholder="请输入记录内容"
          class="content-textarea"
          maxlength="500"
        />
      </view>

      <!-- 记录时间 -->
      <view class="form-item">
        <text class="form-label">健康日期<text class="required">*</text></text>
        <picker 
          mode="date" 
          @change="onRecordDateChange"
          :value="formData.recordDate ? formData.recordDate.split(' ')[0] : ''"
          class="picker"
        >
          <view class="picker-text">{{formData.recordDate ? formData.recordDate.split(' ')[0] : '请选择健康日期'}}</view>
        </picker>
      </view>

      <!-- 备注 -->
      <view class="form-item">
        <text class="form-label">备注</text>
        <textarea 
          v-model="formData.remark" 
          placeholder="请输入备注信息" 
          class="content-textarea"
          maxlength="200"
        />
      </view>

        <!-- 保存按钮 -->
      <button class="submit-btn" @click="saveRecord">保存修改</button>
    </view>
  </view>
</template>

<script>
import { API_BASE } from '@/config/config.js'
import { getUserId } from '@/utils/auth.js'
import { getPetList } from '@/api/pet.js'
import { getDictData } from '@/api/dict.js'

export default {
  computed: {
    selectedPetName() {
      console.log('selectedPetName被调用，formData.petId:', this.formData.petId, 'pets长度:', this.pets.length)
      if (this.formData.petId && this.pets.length > 0) {
        // 尝试多种可能的ID字段名
        const pet = this.pets.find(item => 
          item.petId === this.formData.petId || 
          item.id === this.formData.petId || 
          String(item.petId) === String(this.formData.petId) ||
          String(item.id) === String(this.formData.petId)
        )
        console.log('找到的宠物:', pet)
        if (pet) {
          // 使用与getPetDisplayField相同的逻辑
          return this.getPetDisplayName(pet)
        }
      }
      return ''
    }
  },
  data() {
    return {
      recordId: null,
      formData: {
        type: '',
        content: '',
        reminderId: '', // 提醒ID字段
        recordDate: new Date().toISOString().slice(0, 16).replace('T', ' '), // 记录日期时间字段，设置默认值为当前时间
        petId: '', // 宠物ID字段
        remark: '' // 备注字段
      },
      typeOptions: [],
      typeIndex: 0,
      petIndex: 0,
      pets: []
    }
  },
  onLoad(options) {
    this.recordId = options.id
    if (this.recordId) {
      this.loadRecordDetail(this.recordId)
    }
    this.loadPets()
    this.loadDictData()
  },
  methods: {
    // 获取宠物显示字段名
    getPetDisplayField() {
      if (this.pets.length > 0) {
        const firstPet = this.pets[0]
        // 检查可能的字段名
        if (firstPet.name) return 'name'
        if (firstPet.petName) return 'petName'
        if (firstPet.nickName) return 'nickName'
        if (firstPet.title) return 'title'
        if (firstPet.pet_name) return 'pet_name'
        if (firstPet.nickname) return 'nickname'
        // 如果都没有，返回第一个存在的字符串字段
        for (let key in firstPet) {
          if (typeof firstPet[key] === 'string' && key !== 'id' && key !== 'petId') {
            return key
          }
        }
      }
      return 'name' // 默认值
    },
    
    // 获取宠物显示名称
    getPetDisplayName(pet) {
      if (!pet) return ''
      // 使用与getPetDisplayField相同的优先级
      return pet.name || pet.petName || pet.nickName || pet.title || pet.pet_name || pet.nickname || '未知宠物'
    },
    
    async loadRecordDetail(recordId) {
      try {
        const response = await uni.request({
          url: `${API_BASE}/system/health/${recordId}`,
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          }
        })

        const [error, res] = response
        if (error || !res || res.statusCode !== 200) {
          throw new Error('加载记录失败')
        }

        const recordData = res.data.data || res.data
        
        this.formData = {
          type: recordData.type,
          content: recordData.content,
          reminderId: recordData.reminderId || '', // 提醒ID字段
          recordDate: this.formatDateTime(recordData.recordDate) || new Date().toISOString().slice(0, 16).replace('T', ' '), // 记录日期时间字段，如果没有则使用当前日期时间
          petId: recordData.petId || '', // 宠物ID字段
          remark: recordData.remark || '' // 备注字段
        }
        console.log('加载的记录时间:', this.formData.recordDate);
        
        console.log('记录数据:', recordData)
        console.log('formData.petId:', this.formData.petId)
        console.log('当前pets数组:', this.pets)
        
        // 设置宠物选择器默认值（如果pets已加载）
        if (this.pets.length > 0) {
          // 尝试多种可能的ID字段名
          this.petIndex = this.pets.findIndex(item => 
            item.petId === this.formData.petId || 
            item.id === this.formData.petId || 
            String(item.petId) === String(this.formData.petId) ||
            String(item.id) === String(this.formData.petId)
          )
          console.log('找到的petIndex:', this.petIndex)
          if (this.petIndex === -1) {
            console.log('未找到匹配的宠物，pets数组结构:', JSON.stringify(this.pets[0], null, 2))
          }
        }

        // 设置选择器默认值
        this.typeIndex = this.typeOptions.findIndex(item => item.value === this.formData.type)

      } catch (error) {

        uni.showToast({
          title: '加载记录失败',
          icon: 'none'
        })
      }
    },
    async loadPets() {
      try {
        const userId = getUserId()
        const response = await getPetList(userId)
        
        if (response && response.code === 200) {
          this.pets = response.rows || response.data || []
          console.log('加载的pets数据:', this.pets)
          console.log('pets数组长度:', this.pets.length)
          if (this.pets.length > 0) {
            console.log('第一个宠物对象的结构:', JSON.stringify(this.pets[0], null, 2))
          }
          // 如果已有formData.petId，重新设置宠物选择器默认值
          if (this.formData.petId) {
            // 尝试多种可能的ID字段名
            this.petIndex = this.pets.findIndex(item => 
              item.petId === this.formData.petId || 
              item.id === this.formData.petId || 
              String(item.petId) === String(this.formData.petId) ||
              String(item.id) === String(this.formData.petId)
            )
            console.log('重新设置petIndex:', this.petIndex)
          }
        }
      } catch (error) {

      }
    },
    async loadDictData() {
      try {
        // 加载记录类型字典
        const typeResponse = await getDictData('pet_health_type')
        if (typeResponse && typeResponse.code === 200) {
          this.typeOptions = typeResponse.data.map(item => ({
            label: item.dictLabel,
            value: item.dictValue
          }))
        }
        

      } catch (error) {

        // 如果字典加载失败，使用默认值
        this.typeOptions = [
          { label: '疫苗', value: '疫苗' },
          { label: '驱虫', value: '驱虫' },
          { label: '体检', value: '体检' },
          { label: '体重', value: '体重' }
        ]

      }
    },
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.formData.type = this.typeOptions[this.typeIndex].value
    },
    onPetChange(e) {
      this.petIndex = e.detail.value
      this.formData.petId = this.pets[this.petIndex].petId
    },
    // 记录日期选择事件
    onRecordDateChange(e) {
      this.formData.recordDate = e.detail.value;
    },
    
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      console.log('formatDateTime输入:', dateTime);
      
      // 处理ISO格式时间 (YYYY-MM-DDTHH:mm:ss.sssZ)
      if (dateTime.includes('T')) {
        const datePart = dateTime.split('T')[0];
        const timePart = dateTime.split('T')[1].split('.')[0].substring(0, 5); // 取HH:mm
        const formatted = `${datePart} ${timePart}`;
        console.log('formatDateTime ISO格式处理结果:', formatted);
        return formatted;
      }
      
      // 如果是日期格式（YYYY-MM-DD），添加默认时间
      if (dateTime.length === 10) {
        const formatted = dateTime + ' 00:00';
        console.log('formatDateTime 日期格式处理结果:', formatted);
        return formatted;
      }
      
      // 如果已经是日期时间格式，直接返回
      console.log('formatDateTime 直接返回:', dateTime);
      return dateTime
    },
    




    async saveRecord() {
      if (!this.formData.type || !this.formData.content || !this.formData.petId || !this.formData.recordDate) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }

      // 确保recordDate包含日期和时间，格式为 yyyy-MM-dd HH:mm:ss
      let formattedRecordDate = this.formData.recordDate;
      if (formattedRecordDate) {
        if (formattedRecordDate.includes(' ')) { // 如果包含时间部分
          // 确保时间格式为 HH:mm:ss
          const parts = formattedRecordDate.split(' ');
          const datePart = parts[0];
          let timePart = parts[1];
          
          // 如果时间部分只有 HH:mm，添加 :ss
          if (timePart && timePart.length === 5) {
            timePart += ':00';
          }
          
          formattedRecordDate = `${datePart} ${timePart || '00:00:00'}`;
        } else { // 如果只有日期部分，添加默认时间
          formattedRecordDate = formattedRecordDate + ' 00:00:00';
        }
      }

      try {
        const response = await uni.request({
          url: `${API_BASE}/system/health`,
          method: 'PUT',
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token'),
            'Content-Type': 'application/json'
          },
          data: {
            ...this.formData,
            recordDate: formattedRecordDate,
            id: this.recordId
          }
        })

        const [error, res] = response
        if (error || !res || res.statusCode !== 200) {
          const errorMsg = res?.data?.msg || res?.data?.message || '保存失败'
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          })
          return
        }
        
        const responseData = res.data
        if (responseData && responseData.code === 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })

          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          const errorMsg = responseData?.msg || responseData?.message || '修改失败'
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          })
        }
      } catch (error) {

        uni.showToast({
          title: '修改失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  background: white;
  border-radius: 15rpx;
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  padding-bottom: 20rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  display: flex;
  align-items: center;
  font-weight: bold;
  width: 180rpx;
  flex-shrink: 0;
  margin-right: 20rpx;
}

.required {
  color: #ff0000;
  margin-left: 4rpx;
  font-weight: bold;
}

.form-input {
  flex: 1;
  min-height: 36rpx;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
}

.content-textarea {
  height: 300rpx;
  resize: none;
  flex: 1;
  min-height: 36rpx;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
}

.picker {
  flex: 1;
}

.date-picker .picker-text, .time-picker .picker-text {
  background: transparent;
}



.time-picker {
  flex: 2;
  min-width: 140rpx;
}



.picker-text {
  color: #333;
  min-height: 36rpx;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.textarea {
  height: 120rpx;
  resize: none;
}

.input:focus, .textarea:focus {
  border-color: #007AFF;
}

.submit-btn {
  margin-top: 50rpx;
  background: #007AFF;
  color: white;
  border-radius: 8rpx;
}
</style>